#include "csapp.h"
#include <time.h>

void echo(int connfd, char *haddrp);

int main(int argc, char **argv)
{
  int listenfd,connfd,port1;
  socklen_t clientlen;
  struct sockaddr_storage clientaddr;
  char client_hostname[MAXLINE], client_port[MAXLINE];
  
    if(argc != 2) {
    fprintf(stderr,"usage:%s <post>\n",argv[0]);
	exit(0);
    }
	port1=atoi(argv[1]);
	listenfd = Open_listenfd(port1);
	while(1){
	  clientlen = sizeof(struct sockaddr_storage);
	  connfd = Accept(listenfd,(SA*)&clientaddr,&clientlen);
	  getnameinfo((SA*)&clientaddr,clientlen,client_hostname,MAXLINE,client_port,MAXLINE,0);
	  printf("Connected to (%s, %s)\n",client_hostname,client_port);
	  echo(connfd,client_hostname);
	  close(connfd);
	}
	exit(0);
}

/*void echo(int connfd)
{
  size_t n;
  char buf[MAXLINE];
  rio_t rio;
  
  Rio_readinitb(&rio, connfd);
  while((n = Rio_readlineb(&rio,buf,MAXLINE))!=0){
    printf("server received %d bytes\n",(int)n);
	Rio_writen(connfd,buf,n);
  }
}
*/
void echo(int connfd, char *haddrp)//客户端IP
{
    time_t t; 
    struct tm * lt;

    size_t n; 
    char buf[MAXLINE]; 
    rio_t rio;

    Rio_readinitb(&rio, connfd);
    while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0) { 
    printf("\n客户端IP：%s\n",haddrp);
    printf("服务器实现者学号：20155225\n");
    time (&t);
    lt = gmtime (&t);
    printf ("当前时间为：%d/%d/%d %d:%d:%d\n",lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);
	//Rio_writen(connfd, buf, n);
    }
}
